package com.Shoping.controller;

import com.Shoping.entity.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String methodStr = req.getParameter(Constants.METHOD);
        if(methodStr==null||methodStr.equals("")) {
            methodStr = Constants.HOMEPAGE;
        }
        Class clazz = this.getClass();
        try {
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            Object invoke = method.invoke(this, req, resp);
            if(invoke!=null) {
                String str = (String) invoke;
                String path = str.substring(str.indexOf(Constants.FLAG)+1);
                if(str.startsWith(Constants.FORWARD)) {
                    req.getRequestDispatcher(path).forward(req, resp);
                }else if(str.startsWith(Constants.REDIRECT)) {
                    resp.sendRedirect(path);
                }else {
                    resp.getWriter().write(str);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public String homePage(HttpServletRequest request,HttpServletResponse response) {
        return Constants.FORWARD+"/web";
    }
}
